var header_h, NVTabBar, ajpush, ns, app, UIActionProgress;
var trycount = 0;
app = new Vue({
    el: '#app',
    data: {
        footers: [{
                title: '首页',
                pagetitle: '商家助手',
                name: 'home_index_frm',
                is_active: true,
                normal: 'widget://image/icon/gongzuo1.png',
                highlight: 'widget://image/icon/index_active.png',
                selected: 'widget://image/icon/gongzuo.png',
                icon_width: 25,
                icon_height: 25,
                bd_margin_bottom: -2,
                color_normal: '#999999',
                color_selected: '#ea7825'
            },
            //  {
            //     title: '消息',
            //     pagetitle: '消息中心',
            //     name: 'home_message_frm',
            //     is_active: false,
            //     normal: 'widget://image/icon/xiaoxi1.png',
            //     highlight: 'widget://image/icon/shop_active.png',
            //     selected: 'widget://image/icon/xiaoxi.png',
            //     icon_width: 25,
            //     icon_height: 25,
            //     bd_margin_bottom: -2,
            //     color_normal: '#999999',
            //     color_selected: '#ea7825'
            // },
            // {
            //     title: '商圈',
            //     name: 'home_fsyouxuan_frm',
            //     is_active: false,
            //     normal: 'widget://image/icons/shangquan_normal.png',
            //     highlight: 'widget://image/icons/shangquan_active.png',
            //     selected: 'widget://image/icons/shangquan_active.png',
            //     icon_width: 45,
            //     icon_height: 45,
            //     bd_margin_bottom: 5,
            //     color_normal: '#515151',
            //     color_selected: '#ffc107'
            // },
            {
                title: '订单',
                pagetitle: '订单中心',
                name: 'home_orderlist_frm',
                is_active: false,
                normal: 'widget://image/icon/dingdan1.png',
                highlight: 'widget://image/icon/fuwu_active.png',
                selected: 'widget://image/icon/dingdan.png',
                icon_width: 25,
                icon_height: 25,
                bd_margin_bottom: -2,
                color_normal: '#999999',
                color_selected: '#ea7825'
            }, 
            {
                title: '我的',
                pagetitle: '设置',
                name: 'home_shezhi_frm',
                is_active: false,
                normal: 'widget://image/icon/shezhi1.png',
                highlight: 'widget://image/icon/mine_active.png',
                selected: 'widget://image/icon/shezhi.png',
                icon_width: 25,
                icon_height: 25,
                bd_margin_bottom: -2,
                color_normal: '#999999',
                color_selected: '#ea7825'
            }
        ],
        page_title: '商家助手',
        device_id: '',
        device_type: '',
        show_header: false,
        show_room: false,
        show_title: false,
        show_cart_icon: false,
        show_chat_icon: false,
        show_search_icon: false,
        show_setting: false,
        show_search: false,
        show_door: false,
        form: {
            id: 0,
            type: 0
        },
        // xiaoquname: '商家助手',
        xiaoqulist: []
    },
    methods: {
        open_cart: function() {
            var that = this;
            ns.openWin('dl_gouwuche_frm', '购物车', null, {
                ismain: true
            });
        },
        open_chat: function() {
            var that = this;
            ns.openWin('dl_messagelist_frm', '消息中心', null, {
                ismain: true
            });
        },
        open_search: function() {
            var that = this;
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 100;
            }
            api.openTabLayout({
                hideNavigationBar: true,
                hideTabBar: true,
                useWKWebView: true,
                name: 'searchbar_frm',
                url: './html/dl_searchbar_frm.html',
                delay: delay,
                slidBackEnabled: false,
                vScrollBarEnabled: false,
                pageParam: {
                    searchtype: 1,
                },
                rect: {
                    x: 0,
                    y: 0,
                    w: 'auto',
                    h: 'auto',
                },
                animation: {
                    type: 'movein',
                    subType: 'from_bottom'
                }
            });
        },
        open_xiaoqu: function() {
            var that = this;
            ns.openWin('myxiaoqu_frm', '我的小区', null, {
                needlogin: true,
                ismain: true
            });
        },
        open_setting: function() {
            api.sendEvent({
                name: 'open_setting'
            });
        },
        open_popup: function() {
            api.sendEvent({
                name: 'open_popup'
            });
        },
        open_door: function() {
            api.sendEvent({
                name: 'open_doorcard'
            });
        },
        open_win: function(title, name) {
            var that = this;
            if (name == '') {
                return;
            }
            ns.openWin(name, title, {
                ismain: true
            });
        },
        // get_menus: function() {
        //     var that = this;
        //     var list = [];
        //     for (var i = 0; i < that.footers.length; i++) {
        //         var item = that.footers[i];
        //         var menu = {
        //             w: api.winWidth / 3.0,
        //             bg: {
        //                 marginB: item.bd_margin_bottom,
        //             },
        //             iconRect: {
        //                 w: item.icon_width,
        //                 h: item.icon_height,
        //             },
        //             icon: {
        //                 normal: item.normal,
        //                 highlight: item.highlight,
        //                 selected: item.selected
        //             },
        //             title: {
        //                 text: item.title,
        //                 size: 12.0,
        //                 normal: item.color_normal,
        //                 selected: item.color_selected,
        //                 marginB: 6.0
        //             }
        //         }
        //         list.push(menu);
        //     };
        //     return list;
        // },
        // open_menu: function() {
        //     var that = this;
        //     NVTabBar.open({
        //             styles: {
        //                 bg: '#fff',
        //                 h: 0,
        //                 dividingLine: {
        //                     width: 0.5,
        //                     color: '#eeeeee'
        //                 },
        //                 badge: {
        //                     bgColor: '#ff0',
        //                     numColor: '#fff',
        //                     size: 6.0,
        //                     centerX: 40,
        //                     centerY: 6
        //                 },
        //             },
        //             items: that.get_menus(),
        //             selectedIndex: 0
        //         },
        //         function(ret, err) {
        //             NVTabBar.bringToFront();
        //             if (ret.eventType == 'click') {
        //                 that.openFrame(that.footers[ret.index]);
        //             }
        //             NVTabBar.bringToFront();
        //         }
        //     );
        // },
        openFrame: function(item) {
            var that = this;          
            if (item.name == 'home_self_frm') {
                that.show_room = false;
                that.show_title = true;
                that.show_cart_icon = false;
                that.show_search_icon = false;
                that.show_setting = false;
                that.show_header=false;
                that.show_chat_icon = false;
                that.show_search = false;
                that.show_door = false;
            } 
            else if (item.name == 'home_index_frm') {
                that.show_room = false;
                that.show_title = false;
                that.show_header=true;
                that.show_cart_icon = false;
                that.show_search_icon = false;
                that.show_setting = false;
                that.show_search = false;
                that.show_door = false;
            }
            else if (item.name == 'dl_productlist') {
                that.show_room = false;
                that.show_title = false;
                that.show_header=false;
                that.show_cart_icon = false;
                that.show_search_icon = true;
                that.show_setting = true;
                that.show_search = false;
                that.show_door = false;
            } else if (item.name == 'home_shop_frm') {
                that.show_room = false;
                that.show_title = false;
                that.show_header=false;
                that.show_cart_icon = true;
                that.show_chat_icon = false;
                that.show_search_icon = false;
                that.show_setting = false;
                that.show_search = true;
                that.show_door = false;
            } else {
                that.show_room = false;
                that.show_title = true;
                that.show_header=false;
                that.show_cart_icon = true;
                that.show_chat_icon = true;
                that.show_search_icon = false;
                that.show_setting = false;
                that.show_search = false;
                that.show_door = false;
            }
            // for (var i = 0; i < that.footers.length; i++) {
            //     that.footers[i].is_active = false;
            // }
            item.is_active = true;
            that.page_title = item.pagetitle;
            var header = $api.byId('aui-header');
            $api.fixStatusBar(header);
            var headerH = $api.offset(header).h;
            var frameH = api.winHeight - headerH - 60;
            api.openFrame({
                name: item.name,
                url: './html/' + item.name + '.html',
                bounces: false,
                useWKWebView: true,
                rect: {
                    x: 0,
                    y: 0,
                    w: 'auto',
                    h: 'auto',
                    marginBottom: 10
                }
            });
        },
        //保存极光用户注册id
        save_jg_cid: function() {
            var that = this;
            ajpush.getRegistrationId(function(ret, err) {
                if (ret && ret.id) {
                    that.device_id = ret.id;
                    ns.post({
                        device_id: that.device_id,
                        device_type: that.device_type,
                        action: 'savedeviceid'
                    }, function(succeed, data, err) {

                    }, {
                        ismain: true
                    });
                }
            });
        },
        //初始化
        jp_init: function() {
            var that = this;
            console.log('DDDDD');
            if (that.device_type == 'android') {
                ajpush.init(function(ret, err) {});
            }
            setTimeout(function() {
                // that.jp_setListener();
                that.jp_Add_Listener();
                that.jp_Resume_Push();
                that.save_jg_cid();
                ajpush.setBadge({
                    badge: 0
                });
            }, 2000);
        },
        //APP界面打开状态获取消息
        jp_setListener: function() {
            var that = this;
            ajpush.setListener(function(ret, err) {
                if (ret && ((ret.title && that.device_type == 'ios') || that.device_type == 'android')) {
                    var rep = ret.extra;
                    api.getPrefs({
                        key: 'uid'
                    }, function(res, err) {
                        if (res.value) {
                            ajpush.setBadge({
                                badge: 0
                            });
                            that.jp_process(rep, true);
                        } else {
                            api.sendEvent({
                                name: 'onlogin'
                            });
                        }
                    });
                }
            });
        },
        //APP界面隐藏状态获取消息
        jp_Add_Listener: function() {
            var that = this;
            // alert(JSON.stringify('rep'));
            api.addEventListener({
                name: 'appintent'
            }, function(ret, err) {
                // alert(JSON.stringify(ret));
                if (ret && ret.appParam.ajpush) {
                    var rep = ret.appParam.ajpush.extra;
                    api.getPrefs({
                        key: 'uid'
                    }, function(res, err) {
                        
                        if (res.value) {
                            that.jp_process(rep, true);
                        } else {
                            api.sendEvent({
                                name: 'onlogin'
                            });
                        }
                    });
                }
            });
            api.addEventListener({
                name: 'noticeclicked'
            }, function(ret, err) {
                if (ret && ret.value) {
                    var rep = ret.value.extra;
                    api.getPrefs({
                        key: 'uid'
                    }, function(res, err) {
                        if (res.value) {
                            ajpush.setBadge({
                                badge: 0
                            })
                            that.jp_process(rep, true);
                        } else {
                            api.sendEvent({
                                name: 'onlogin'
                            });
                        }
                    });
                }
            });
            api.addEventListener({
                name: 'pause'
            }, function(ret, err) {
                ajpush.onPause(); //监听应用进入后台
                that.jp_Resume_Push();
            });
            api.addEventListener({
                name: 'resume'
            }, function(ret, err) {
                ajpush.onResume(); //监听应用恢复到前台
                that.jp_Resume_Push();
            });
        },
        //断开重连
        jp_Resume_Push: function() {
            var that = this;
            if (that.jg_timeout) {
                clearTimeout(that.jg_timeout);
                that.jg_timeout = null;
            }
            setTimeout(function() {
                that.jp_resumePush();
            }, 1000);
        },
        //断开重连
        jp_resumePush: function() {
            var that = this;
            ajpush.isPushStopped(function(ret, err) {
                if (!ret || ret.isStopped != 0) {
                    ajpush.resumePush(function(ret, err) {});
                }
                that.jg_timeout = setTimeout(function() {
                    that.jp_resumePush();
                }, 10 * 1000);
            });
        },
        jp_openwin: function(name, title, params) {
            var that = this;
            api.closeToWin({
                name: 'root'
            });
            setTimeout(function() {
                ns.openWin(name, title, params, {
                    ismain: true
                });
            }, 500);
        },
        jp_process: function(rep, pop_required) {
            console.log(JSON.stringify(rep));
            var that = this;
            var title = '';
            var name = '';
            var params = {};
            var code = rep.code;
            var type = rep.type;
            if (type == 'wechatmsg_gonggao') {
                if (code == 101) {
                    title = '物业公告';
                    name = 'sqgonggao_detail_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id
                    }
                }
            }
            if (type == 'wechatmsg_news') {
                if (code == 201) {
                    title = '小区新闻';
                    name = 'xiaoqunews_detail_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id
                    }
                }
            }
            if (type == 'mallproduct_tuan') {
                if (code == 301) {
                    title = '商品详情';
                    name = 'dl_product_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id,
                        type: 16
                    }
                }
            }
            if (type == 'mallproduct_xianshi') {
                if (code == 401) {
                    title = '商品详情';
                    name = 'dl_product_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id,
                        type: 16
                    }
                }
            }
            if (type == 'mallbirthday_coupon') {
                if (code == 501) {
                    title = '我的优惠券';
                    name = 'mycoupon_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                    }
                }
            }
            if (type == 'mallorder_refund') {
                if (code == 601) {
                    title = '订单详情';
                    name = 'ordercomplete_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id
                    }
                }
            }
            if (type == 'mallorder_shipped') {
                if (code == 701) {
                    title = '订单详情';
                    name = 'ordercomplete_frm';
                    params = {
                        title: title,
                        url: name + '.html',
                        id: rep.id
                    }
                }
            }
            if (type) {
                if (pop_required) {
                    api.confirm({
                        title: '提示',
                        msg: rep.msg,
                        buttons: ['点击查看', '稍后再说']
                    }, function(ret, err) {
                        var index = ret.buttonIndex;
                        if (index == 1) {
                            that.jp_openwin(name, title, params);
                        }
                    });
                } else {
                    that.jp_openwin(name, title, params);
                }
            }
        },
        open_sub_page: function() {
            var that = this;
            if (that.form.id > 0 && that.form.type > 0) {
                var that = this;
                var name = '';
                var title = '';
                if (that.form.type == 1) {
                    name = 'dl_product_frm';
                    title = '商品详情';
                    ns.openWin(name, title, {
                        title: title,
                        url: name + '.html',
                        id: that.form.id,
                        type: 16
                    }, {
                        ismain: true
                    });
                    return;
                }
                if (that.form.type == 2) {
                    name = 'business_frm';
                    title = '商家详情';
                    ns.openWin(name, title, {
                        title: title,
                        url: name + '.html',
                        id: that.form.id,
                        searchtype: 2
                    }, {
                        ismain: true
                    });
                    return;
                }
                if (that.form.type == 3) {
                    name = 'sqgonggao_detail_frm';
                    title = '社区公告';
                    ns.openWin(name, title, {
                        title: title,
                        url: name + '.html',
                        id: that.form.id
                    }, {
                        ismain: true
                    });
                    return;
                }
                if (that.form.type == 4) {
                    name = 'xiaoqunews_detail_frm';
                    title = '小区新闻';
                    ns.openWin(name, title, {
                        title: title,
                        url: name + '.html',
                        id: that.form.id
                    }, {
                        ismain: true
                    });
                    return;
                }
                if (that.form.type == 5) {
                    name = 'servicedetail_frm';
                    title = '生活服务';
                    ns.openWin(name, title, {
                        title: title,
                        url: name + '.html',
                        id: that.form.id
                    }, {
                        ismain: true
                    });
                    return;
                }
            }
        },
        checkupdate: function() {
            var that = this;
            console.log(JSON.stringify(api.appVersion));
            ns.post({
                action: 'getappversion',
                version: api.appVersion,
                versiontype: api.systemType,
                APPType: 1
            }, function(succeed, data, err) {
                if (succeed) {
                    var result = data;
                    if (result && result.update == true && result.closed == false) {
                        var str = '';
                        if (result.version) {
                            str += '新版本型号:' + result.version + ';';
                        }
                        if (result.versionDes) {
                            str += '更新描述:' + result.versionDes + ';';
                        }
                        if (result.time) {
                            str += '发布时间:' + result.time + ';';
                        }
                        if (result.isforceupdate) {
                            api.alert({
                                title: '有新的版本,是否下载并安装',
                                msg: str,
                            }, function(ret, err) {
                                if (api.systemType == "android") {
                                    that.downloadapp(result.source);
                                }
                                if (api.systemType == "ios") {
                                    api.installApp({
                                        appUri: result.source
                                    });
                                }
                            });
                            return;
                        }
                        api.confirm({
                            title: '有新的版本,是否下载并安装 ',
                            msg: str,
                            buttons: ['确定', '取消']
                        }, function(ret, err) {
                            if (ret.buttonIndex == 1) {
                                if (api.systemType == "android") {
                                    that.downloadapp(result.source);
                                }
                                if (api.systemType == "ios") {
                                    api.installApp({
                                        appUri: result.source
                                    });
                                }
                            }
                        });
                    }
                }
            }, {
                ismain: true
            });
        },
        downloadapp: function(url) {
            var that = this;
            that.UIActionProgressOpen();
            api.download({
                url: url,
                report: true
            }, function(ret, err) {
                if (ret && 0 == ret.state) { /* 下载进度 */
                    that.UIActionProgressSetData(ret.percent);
                }
                if (ret && 1 == ret.state) { /* 下载完成 */
                    UIActionProgress.close();
                    var savePath = ret.savePath;
                    api.installApp({
                        appUri: savePath
                    });
                }
            });
        },
        UIActionProgressOpen: function() {
            UIActionProgress.open({
                maskBg: 'rgba(0,0,0,0.5)',
                styles: {
                    h: 108,
                    bg: '#fff',
                    title: {
                        size: 13,
                        color: '#000',
                        marginT: 10
                    },
                    msg: {
                        size: 12,
                        color: '#000',
                        marginT: 5
                    },
                    lable: {
                        size: 12,
                        color: '#696969',
                        marginB: 5
                    },
                    progressBar: {
                        size: 2,
                        normal: '#000',
                        active: '#4876FF',
                        marginB: 35,
                        margin: 5
                    }
                },
                data: {
                    title: '正在更新',
                    msg: '开始下载',
                    value: 0
                }
            }, function(ret) {
                // api.alert({ msg: JSON.stringify(ret) });
            });
        },
        UIActionProgressSetData: function(value) {
            UIActionProgress.setData({
                data: {
                    title: '正在更新...',
                    msg: '',
                    value: value
                }
            });
        },
        get_xiaoqu_list: function() {
            var that = this;
            ns.post({
                action: 'getmyxiaoqulist',
            }, function(succeed, data, err) {
                if (succeed) {
                    that.xiaoqulist = data.list;
                    if (that.xiaoqulist.length > 0) {
                        that.xiaoquname = that.xiaoqulist[0].name;
                    }
                    api.removePrefs({
                        key: 'open_door_ring_path'
                    });
                    if (data.FilePath != '') {
                        that.download_video_file(data.FilePath, data.FileName);
                    }
                }
            }, {
                ismain: true
            });
        },
        download_video_file: function(filepath, filename) {
            var that = this;
            filename = (filename == '' ? 'doorring.mp3' : filename);
            var video_local_path = 'fs://saasyy/mall/' + filename;
            api.download({
                url: filepath,
                savePath: video_local_path,
                report: true,
                cache: true,
                allowResume: true
            }, function(ret, err) {
                if (ret.state == 1) {
                    api.setPrefs({
                        key: 'open_door_ring_path',
                        value: video_local_path
                    });
                }
            });
        },
        play_open_door_ring: function() {
            var that = this;
            var open_door_ring_path = api.getPrefs({
                sync: true,
                key: 'open_door_ring_path'
            });
            open_door_ring_path = (open_door_ring_path == '' ? 'widget://res/doorring.mp3' : open_door_ring_path);
            api.startPlay({
                path: open_door_ring_path
            }, function(ret, err) {});
        },
        open_room_list: function() {
            var that = this;
            if (that.xiaoqulist.length == 0) {
                return;
            }
            api.sendEvent({
                name: 'open_xiaoqu_list'
            })
        },
        open_searchbar: function() {
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 100;
            }
            api.openTabLayout({
                hideNavigationBar: true,
                hideTabBar: true,
                useWKWebView: true,
                name: 'searchbar_frm',
                url: './html/searchbar_frm.html',
                delay: delay,
                slidBackEnabled: false,
                vScrollBarEnabled: false,
                pageParam: {
                    searchtype: 1,
                },
                rect: {
                    x: 0,
                    y: 0,
                    w: 'auto',
                    h: 'auto',
                },
                animation: {
                    type: 'movein',
                    subType: 'from_bottom'
                }
            });
        },
        LoginSocketInit: function() {
            var that = this;
            if (trycount > 3) {
                return;
            }
            ns.post({
                action: 'socketinit'
            }, function(succeed, data, err) {
                if (succeed) {
                    try {
                        LoginConnect.init(data);
                        LoginConnect.submit();
                    } catch (e) {
                        trycount++;
                        that.LoginSocketInit();
                    }
                }
            }, {
                ismain: true
            });
        },
        get_all: function() {
            var that = this;
            setTimeout(function() {
                // that.open_menu();
                that.openFrame(app.footers[0]);
            }, 100);
            //that.get_xiaoqu_list();
            setTimeout(function() {
                that.LoginSocketInit();
            }, 2000);
            setTimeout(function() {
                that.jp_init();
            }, 3000);
        }
    }
});
apiready = function() {
    api.parseTapmode();
    app.form.id = api.pageParam.id || 0;
    app.form.type = api.pageParam.type || 0;
    ns = window.Foresight.Util;
    app.device_type = api.systemType;
    ajpush = api.require('ajpush');
    // NVTabBar = api.require('NVTabBar');
    UIActionProgress = api.require('UIActionProgress');
    app.get_all();
    api.addEventListener({
        name: 'mall_onclick'
    }, function() {
        // NVTabBar.setSelect({
        //     index: 1,
        //     selected: true,
        // });
        app.openFrame(app.footers[1]);
        // NVTabBar.bringToFront();
    });

    api.addEventListener({
        name: 'close_intro_success'
    }, function(ret) {
        app.form.id = ret.value.id || 0;
        app.form.type = ret.value.type || '';
        setTimeout(function() {
            app.open_sub_page();
        }, 1000);
    });
    var last_out_time;
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {
        if (last_out_time && last_out_time.valueOf() >= (new Date().valueOf() - 1000)) {
            api.closeWidget({
                silent: true
            });
            return;
        }
        last_out_time = new Date();
        api.toast({
            msg: '再按一次退出程序',
            duration: 1000
        });
    });
    api.addEventListener({
        name: 'choose_my_xiaoqu'
    }, function(ret) {
        app.xiaoquname = ret.value.name;
    });
    api.addEventListener({
        name: 'onlogin'
    }, function(ret) {
        ns.removePrefs(ns.checkloginstatuskey);
        app.LoginSocketInit();
        // setTimeout(function() {
        //     NVTabBar.setSelect({
        //         index: 0,
        //         selected: true,
        //     });
        //     app.openFrame(app.footers[0]);
        //     NVTabBar.bringToFront();
        // }, 500);
    });
    api.addEventListener({
        name: 'opendoorsuccess'
    }, function(ret) {
        app.play_open_door_ring();
    });
};
